#!/bin/sh
set -eu
PIBOT_LAUNCH_DIR=$(CDPATH= cd -- "$(dirname -- "$(readlink -f -- "$0")")" && pwd)
# The doctor has no renderer: keep it usable without DISPLAY and without creating an owner.
for PIBOT_LAUNCH_ARG in "$@"; do
  if [ "$PIBOT_LAUNCH_ARG" = "--sandbox-doctor" ]; then
    exec "$PIBOT_LAUNCH_DIR/resources/bin/node" "$PIBOT_LAUNCH_DIR/resources/app.asar.unpacked/out/main/sandbox-doctor.js"
  fi
done
# The check runs on the bundled helper Node: Pi Bot's own executable has RunAsNode off.
PIBOT_APP_BINARY="$PIBOT_LAUNCH_DIR/pi-bot-bin" "$PIBOT_LAUNCH_DIR/resources/bin/node" "$PIBOT_LAUNCH_DIR/resources/app.asar.unpacked/out/main/linux-sandbox-check.js" "$@" &
PIBOT_CHECK_PID=$!
trap 'kill -TERM "$PIBOT_CHECK_PID" 2>/dev/null || :; wait "$PIBOT_CHECK_PID" 2>/dev/null || :; exit 1' INT TERM HUP
if wait "$PIBOT_CHECK_PID"; then
  trap - INT TERM HUP
else
  exit "$?"
fi
unset ELECTRON_RUN_AS_NODE
exec "$PIBOT_LAUNCH_DIR/pi-bot-bin" --disable-setuid-sandbox "$@"
